package com.fgsecure.apjhnou.app;

import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fgsecure.apjhnou.adapter.CategoryAdapter;
import com.fgsecure.apjhnou.info.Global;
import com.fgsecure.apjhnou.quickactions.ActionItem;
import com.fgsecure.apjhnou.quickactions.QuickAction;

public class SubjectActivity extends Activity {
	private ListView listViewSubject;
	private Vector<Object> vLessons;
	final Context context = this;
	private static final int ID_UP = 1;
	private static final int ID_DOWN = 2;
	private static final int ID_NEW = 3;
	private static final int ID_EDIT = 4;
	private static final int ID_DEL = 5;
	private int positionLongClick = 0;
	String[] values = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listview_item);
		initData();
	}

	public void initData() {
		Vector<Object> vSubject = Global.getvObj();
		values = new String[vSubject.size() / 2];
		Integer valuesNum = 0;
		vLessons = new Vector<Object>();
		for (int i = 0; i < vSubject.size(); i = i + 2) {
			values[valuesNum++] = (String) vSubject.get(i);
			Vector<Object> lessons = (Vector<Object>) vSubject.get(i + 1);
			vLessons.add(lessons);
		}
		CategoryAdapter adapter = new CategoryAdapter(this,
				R.layout.listview_item_row, values);
		listViewSubject = (ListView) findViewById(R.id.listViewItem);
		View header = (View) getLayoutInflater().inflate(
				R.layout.listview_header_row, null);
		listViewSubject.addHeaderView(header);
		listViewSubject.setAdapter(adapter);
		final Intent intent = new Intent(this, LessonsActivity.class);
		ActionItem downItem = new ActionItem(ID_DOWN, "Down", getResources()
				.getDrawable(R.drawable.menu_down_arrow));
		ActionItem upItem = new ActionItem(ID_UP, "Up", getResources()
				.getDrawable(R.drawable.menu_up_arrow));
		ActionItem addItem = new ActionItem(ID_NEW, "New", getResources()
				.getDrawable(R.drawable.menu_add));
		ActionItem editItem = new ActionItem(ID_EDIT, "Edit", getResources()
				.getDrawable(R.drawable.menu_edit));
		ActionItem delItem = new ActionItem(ID_DEL, "Delete", getResources()
				.getDrawable(R.drawable.menu_del));

		// orientation
		final QuickAction quickAction = new QuickAction(this,
				QuickAction.HORIZONTAL);

		// add action items into QuickAction
		quickAction.addActionItem(addItem);
		quickAction.addActionItem(editItem);
		quickAction.addActionItem(delItem);

		// Set listener for action item clicked
		quickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						ActionItem actionItem = quickAction.getActionItem(pos);
						// here we can filter which action item was clicked with
						// pos or actionId parameter
						if (actionId == ID_NEW) {
							dialogAdd();
						} else if (actionId == ID_EDIT) {
							if (positionLongClick != 0)
								dialogEdit();
						} else if (actionId == ID_DEL) {
							if (positionLongClick != 0)
								dialogDelete();
						}
					}
				});

		listViewSubject
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					public boolean onItemLongClick(AdapterView<?> adapter,
							View view, int position, long id) {
						positionLongClick = position;
						quickAction.show(view);
						return false;
					}
				});
		listViewSubject.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position > 0) {
					Global.setSubject(position - 1);
					Vector<Object> menu = Global.readXML();
					Vector<Object> vSubject = (Vector<Object>) menu.get(Global
							.getCategory() * 2 + 1);
					Vector<Object> lessons = (Vector<Object>) vSubject
							.get(Global.getSubject() * 2 + 1);
					Global.setvObj(lessons);
					startActivity(intent);
				}
			}
		});
	}

	public void addSubject(String name) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		NodeList nList = root.getElementsByTagName("category");
		Node nNode = nList.item(Global.getCategory());
		if (nNode.getNodeType() == Node.ELEMENT_NODE) {
			Element category = (Element) nNode;
			Element subject = doc.createElement("subject");
			subject.setAttribute("name", name);
			category.appendChild(subject);
		}
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	public void delSubject() throws ParserConfigurationException, SAXException,
			IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		Element category = (Element) root.getElementsByTagName("category")
				.item(Global.getCategory());
		NodeList nList = category.getElementsByTagName("subject");
		Node nNode = nList.item(positionLongClick - 1);
		category.removeChild(nNode);
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	public void editCategory(String name) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		Element category = (Element) root.getElementsByTagName("category")
				.item(Global.getCategory());
		NodeList nList = category.getElementsByTagName("subject");
		Node nNode = nList.item(positionLongClick - 1);
		Element eElement = (Element) nNode;
		eElement.setAttribute("name", name);
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	private void restartFirstActivity() {
		Vector<Object> menu = Global.readXML();
		Vector<Object> vSubject = (Vector<Object>) menu.get(Global
				.getCategory() * 2 + 1);
		Global.setvObj(vSubject);
		Intent intent = getIntent();
		finish();
		startActivity(intent);
	}

	public void dialogAdd() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_category, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.typeTextTextView);
		typeText.setText(context.getString(R.string.text_subject));
		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							addSubject(userInput.getText().toString().trim());
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}

	public void dialogDelete() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_delete, null);
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.itemDelTextView);
		typeText.setText(values[positionLongClick - 1]);
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							delSubject();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}

	public void dialogEdit() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_category, null);
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.typeTextTextView);
		typeText.setText(context.getString(R.string.text_subject));
		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);
		userInput.setText(values[positionLongClick - 1]);
		userInput.selectAll();
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							editCategory(userInput.getText().toString().trim());
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}
}